package com.warrior.main;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.facebook.Request;
import com.facebook.Request.Callback;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.NewPermissionsRequest;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.facebook.widget.ProfilePictureView;
import com.facebook.widget.WebDialog.FeedDialogBuilder;
import com.warrior.main.MyFacebook.ISessionState;

public class MyFacebook implements StatusCallback{

	private ISessionState iSessionState;
	private GraphUser user;
	public static final String PUBLISH_PERMISSION = "publish_actions";
	private Drawable myDrawableProfilePicture,competitorDrawableProfilePicture;
	private ProfilePictureView myProfilePictureView,competitorProfilePictureView;
	private String myUserName = "",competitorUserName = "";
	private String myUserId = "",competitorUserID = "";
	private Context context;
	
	public MyFacebook(Context context){
		this.context = context;
	}
	
	public Session getCurrentSession(){
		return Session.getActiveSession();
	}
	public GraphUser getUser() {	
		return user;
	}
	public ProfilePictureView getMyProfilePictureView() {
		return myProfilePictureView;
	}
	public ProfilePictureView getCompetitorProfilePictureView() {
		return competitorProfilePictureView;
	}
	public Drawable getMyProfilePicture() {
		return myDrawableProfilePicture;
	}
	public Drawable getCompetitorProfilePicture() {
		return competitorDrawableProfilePicture;
	}
	public String getMyUserName() {
		return myUserName;
	}
	public String getCompetitorUserName() {
		return competitorUserName;
	}
	public String getMyUserId() {
		return myUserId;
	}
	public String getCompetitorUserId() {
		return competitorUserID;
	}
	public boolean isOpenedConnection() {
		if(getCurrentSession() == null){
			return false;
		}
		return getCurrentSession().isOpened();
	}
	public boolean isReadyOpenConnection(){
		boolean isReady = false;
		if(getCurrentSession() == null ||
				!isOpenedConnection()){
			isReady = true;
		}
		return isReady;
	}
	public void setMyProfilePictureView(ProfilePictureView myProfilePictureView) {
		this.myProfilePictureView = myProfilePictureView;
	}
	public void setCompetitorProfilePictureView(
			ProfilePictureView competitorProfilePictureView) {
		this.competitorProfilePictureView = competitorProfilePictureView;
	}
	public void setMyProfilePicture(Drawable myDrawableProfilePicture) {
		this.myDrawableProfilePicture = myDrawableProfilePicture;
	}
	public void setCompetitorProfilePicture(Drawable competitorDrawableProfilePicture) {
		this.competitorDrawableProfilePicture = competitorDrawableProfilePicture;
	}
	public void setMyUserName(String myUserName) {
		this.myUserName = myUserName;
	}
	public void setCompetitorUserName(String competitorUserName) {
		this.competitorUserName = competitorUserName;
	}
	public void setMyUserId(String myUserId) {
		this.myUserId = myUserId;
	}
	public void setCompetitorUserID(String competitorUserID) {
		this.competitorUserID = competitorUserID;
	}
	public void resetDataCompetitor(){
		setCompetitorUserID("");
		setCompetitorUserID("");
		setCompetitorProfilePicture(null);
	}
	static public Drawable convertToDrawable(Context context,ProfilePictureView profilePictureView){
		// convert profilePictureView to Bitmap and so convert to Drawable
		profilePictureView.getDrawingCache();
		ImageView fbImage = ((ImageView)profilePictureView.getChildAt(0));
		Bitmap    bitmap  = ((BitmapDrawable) fbImage.getDrawable()).getBitmap();
		return new BitmapDrawable(context.getResources(),bitmap);
	}
	public Drawable buildCompetitorDrawableProfilePicture(
			Context context,String id) {
		ProfilePictureView competitorProfilePictureView = new ProfilePictureView(context);
		competitorProfilePictureView.setProfileId(id);
		return MyFacebook.convertToDrawable(context, competitorProfilePictureView);
	}
	public void setStateLoginListener(ISessionState iSessionState){
		this.iSessionState = iSessionState;
	}
	public void openSession(Activity activity){
		// start Facebook Login
	    Session.openActiveSession(activity, true, this); 
	}
	public void closeSession(){
		if(getCurrentSession() != null){
			getCurrentSession().closeAndClearTokenInformation();
		}
		user = null;
		iSessionState.facebookCloseSession();
	}
	public void showUploadPostDialog(Activity activity){
		FeedDialogBuilder dialog = new FeedDialogBuilder(activity, getCurrentSession());
	    dialog.build().show();
	}
	public void addPermission(Activity activity,String permission){
		NewPermissionsRequest permissions = new NewPermissionsRequest
				(activity, Arrays.asList(permission));
		getCurrentSession().requestNewPublishPermissions(permissions);
	}
	public boolean isFoundPermission(String permissionSearch){
		boolean retValue = false;
		for (String permission : getCurrentSession().getPermissions()) {
			Log.d(MyLog.FACEBOOK,permission);
			if(permissionSearch.equals(permission)){
				retValue = true;
				break;
			}
		}
		Log.d(MyLog.FACEBOOK,"isFound=" + retValue);
		return retValue;
	}
	public void writePost(String post,final Activity activity){
		Request.executeStatusUpdateRequestAsync(getCurrentSession(), post ,new Callback() {
			public void onCompleted(Response response) {
				String text = "post uploaded";
				if(response.getError() != null){
					text = response.getError().getErrorMessage();
					Log.d(MyLog.FACEBOOK,text);
				}
				Toast.makeText(activity, text, Toast.LENGTH_LONG).show();
			}
		});
	}
	public void openedsesions(){
		// make request to the /me API
	    Request.executeMeRequestAsync(Session.getActiveSession(), new Request.GraphUserCallback() {

	    	// callback after Graph API response with user object
	        @Override
	        public void onCompleted(GraphUser user, Response response) {
	        	if (user != null) {
	        		MyFacebook.this.user = user;
	        		iSessionState.facebookOpenSession(isOpenedConnection(), null);
	        	}
	        }
	      });
	  }
    // callback when session changes state
    public void call(Session s, SessionState state, Exception exception) {
    	Session.setActiveSession(s);
  	  	switch(state){
  	  		case OPENING:{
  	  			Log.d(MyLog.FACEBOOK,"opening");
  	  			break;
  	  		}
  	  		case OPENED:{
  	  			Log.d(MyLog.FACEBOOK,"opend");
  	  			openedsesions();
  	  			break;
	    	}
  	  		case CLOSED:{
  	  			Log.d(MyLog.FACEBOOK,"closed");
  	  			closeSession();
  	  			break;
  	  		}
  	  		case CLOSED_LOGIN_FAILED:{
  	  			Log.d(MyLog.FACEBOOK,"closed login falied");
  	  			break;
  	  		}
  	  		case CREATED:{
  	  			Log.d(MyLog.FACEBOOK,"created");
  	  			break;
  	  		}
  	  		case OPENED_TOKEN_UPDATED:{
  	  			Log.d(MyLog.FACEBOOK,"opened token uptdated");
  	  			break;
  	  		}
  	  		case CREATED_TOKEN_LOADED:{
  	  			Log.d(MyLog.FACEBOOK,"created token loaded");
  	  			break;
  	  		}
  	  	}
  	 
    }
	interface ISessionState{
		void facebookOpenSession(boolean isSuccess,String exception);
		void facebookCloseSession();
	}
	
	
	
	
	
	

	static public void printHashKey(Context context,String packageName) {

	      try {
	          PackageInfo info = context.getPackageManager().getPackageInfo(packageName,
	                  PackageManager.GET_SIGNATURES);
	          for (Signature signature : info.signatures) {
	              MessageDigest md = MessageDigest.getInstance("SHA");
	              md.update(signature.toByteArray());
	              Log.d("TEMPTAGHASH KEY:",
	                      Base64.encodeToString(md.digest(), Base64.DEFAULT));
	              
	          }
	      } catch (NameNotFoundException e) {
	    	  Log.d(MyLog.FACEBOOK_EXEPTION,e.getMessage());

	      } catch (NoSuchAlgorithmException e) {
	    	  Log.d(MyLog.FACEBOOK_EXEPTION,e.getMessage());
	      }

	  }

	
}
